import { modifyAtlas } from '@/api/premium/content/atlas'
import {
  MaterialApi,
  removeMaterialAtlas,
} from '@/api/premium/content/material'
import { AtlasItem } from '@/api/premium/content/model/atlasModel'
import { RemoveMaterialAtlasRequest } from '@/api/premium/content/model/materialModel'
import { MaterialItem } from '@/components/ItemList/MaterialList/types'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import { computed, Ref } from 'vue'

const useOperateAtlasMaterialList = (
  fetchAtlasList: AsyncFun,
  fetchMaterialList: AsyncFun,
  currentAtlasItem: Ref<AtlasItem | undefined>
) => {
  const store = useStore()
  /**
   * 删除图集列表中的指定某一个素材
   *
   * @param material 指定素材
   */
  const deleteMaterialInAtlas = async (material: MaterialItem) => {
    if (currentAtlasItem.value) {
      const reqData: RemoveMaterialAtlasRequest = {
        materialId: material.id,
        data: [currentAtlasItem.value.id],
      }
      await removeMaterialAtlas(reqData)
      message.success('移除成功')
      await fetchMaterialList()
    } else {
      message.error('当前图集信息有问题, 请检查！')
    }
  }
  const removeMaterialAtlasLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.REMOVE_MATERIAL_ATLAS)
  )

  /**
   * 设置指定素材的预览图为当前图集的封面
   */
  const setAtlasImgByMaterial = async (material: MaterialItem) => {
    if (currentAtlasItem.value) {
      const { id } = currentAtlasItem.value
      const { image } = material
      const reqData = { id, imgUrl: image }
      await modifyAtlas(reqData)
      message.success('修改封面成功')
      await fetchAtlasList()
    } else {
      message.error('当前图集信息有问题, 请检查！')
    }
  }

  return {
    deleteMaterialInAtlas,
    removeMaterialAtlasLoading,
    setAtlasImgByMaterial,
  }
}

export default useOperateAtlasMaterialList
